package com.zcs.app.lucky.mock

import kotlinx.coroutines.*

fun main(args: Array<String>) {
    println("HelloKotlin")
    runBlocking {
        // KotlinDemo().testAsync()
        KotlinDemo().testJob()
    }
}

class KotlinDemo {
    suspend fun testAsync() {
        val delay: Long = 998
        println("测试开始 ${Thread.currentThread()}")
        val async = GlobalScope.async {
            println("测试延迟开始 ${Thread.currentThread()}")
            delay(delay)
            println("倒计时：3【${System.currentTimeMillis()}】")
            delay(delay)
            println("倒计时：2【${System.currentTimeMillis()}】")
            delay(delay)
            println("倒计时：1【${System.currentTimeMillis()}】")
            delay(delay)
            for (i in 1..100) {
                println("倒计时：$i【${System.currentTimeMillis()}】")
                delay(delay)
            }
            println("测试延迟结束")
            return@async "666666"
        }
        println("测试结束")
        println("测试返回值：" + async.await())
    }

    suspend fun testJob() {
        println("=== testJob ===")
        val job = GlobalScope.launch(Dispatchers.Default, CoroutineStart.LAZY) {
            println("=== job start ===")
            try {
                withTimeout(8888) {
                    var c = 1
                    while (true) {
                        delay(998)
                        println("c = ${c++}")
                    }
                }
            } catch (e: TimeoutCancellationException) {
                e.printStackTrace()
                println("=== onTimeout with isActive[${isActive}] ===")
                if (isActive)
                    cancel()
            }
        }
        job.start()
        delay(10000)
        println("=== job cancel with job.isActive[${job.isActive}] ===")
        if (job.isActive)
            job.cancel()
    }
}